package com.example.asus.coolweather;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.util.Util;
import com.example.asus.coolweather.db.City;
import com.example.asus.coolweather.db.County;
import com.example.asus.coolweather.db.Province;
import com.example.asus.coolweather.util.HttpUtil;
import com.example.asus.coolweather.util.Utility;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by asus on 2017/8/14.
 */

public class ChooseAreaFragment extends Fragment {
    public static final  int LEVEL_PROVINCE = 0;
    private static final int LEVEL_CITY = 1;
    private static final int LEVEL_COUNTY = 2;
    private ProgressDialog mProgressDialog ;
    private TextView mTitle;
    private Button mBack;
    private ListView mListView;
    private ArrayAdapter<String> mArrayAdapter;
    private List<String> mDataList = new ArrayList<>();
    private List<Province> mProvinceList ;
    private List<City> mCityList;
    private List<County> mCountyList;
    private Province mSelectedProvince;
    private City mSelectedCity;
    private int mCurrentLevel;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area,container,false);
        mTitle = view.findViewById(R.id.tv_title);
        mBack = view.findViewById(R.id.btn_back);
        mListView = view.findViewById(R.id.lv_listview);
        LitePal.getDatabase();
        mArrayAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,mDataList);

        mListView.setAdapter(mArrayAdapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mCurrentLevel == LEVEL_PROVINCE){
                    mSelectedProvince = mProvinceList.get(i);
                    queryCities();

                }else if (mCurrentLevel == LEVEL_CITY){
                    mSelectedCity = mCityList.get(i);
                    queryCounties();

                }
                else if (mCurrentLevel == LEVEL_COUNTY){
                    String weatherId = mCountyList.get(i).getmWeatherId();
                    if (getActivity() instanceof MainActivity){
                        Intent intent = new Intent(getActivity(),WeatherActivity.class);
                        intent.putExtra("weather_id",weatherId);
                        startActivity(intent);
                        getActivity().finish();
                    }else if (getActivity() instanceof WeatherActivity){
                        WeatherActivity activity = (WeatherActivity) getActivity();
                        activity.drawerLayout.closeDrawers();
                        activity.swipeRefreshLayout.setRefreshing(true);
                        activity.requestWeather(weatherId);
                        Log.d("Fragement","weather");
                    }

                }
            }
        });

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrentLevel == LEVEL_COUNTY){
                    queryCities();
                }else if (mCurrentLevel == LEVEL_CITY){
                    queryProvinces();
                }
            }
        });
        queryProvinces();
    }


    private void queryProvinces(){
        mTitle.setText("中国");
        mBack.setVisibility(View.GONE);
        mProvinceList = DataSupport.findAll(Province.class);
        if (mProvinceList.size()>0){
            mDataList.clear();
            for (Province province : mProvinceList){
                mDataList.add(province.getmProvinceName());
            }

            mArrayAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            mCurrentLevel = LEVEL_PROVINCE;
        }else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address,"province");

        }

    }

    private void queryCities(){
        mTitle.setText(mSelectedProvince.getmProvinceName());
        mBack.setVisibility(View.VISIBLE);
        mCityList = DataSupport.where("mProvinceId = ?",String.valueOf(mSelectedProvince.getId())).find(City.class);
        if (mCityList.size()>0){
            mDataList.clear();
            for (City city : mCityList){
                mDataList.add(city.getmCityName());
            }
            mArrayAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            mCurrentLevel = LEVEL_CITY;
        }else {
            int provinceCode = mSelectedProvince.getmProcvinceCode();
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address,"city");
        }
    }


    private void queryCounties(){
        mTitle.setText(mSelectedCity.getmCityName());
        mBack.setVisibility(View.VISIBLE);
        mCountyList = DataSupport.where("cityId = ?",String.valueOf(mSelectedCity.getId())).find(County.class);

        if (mCountyList.size()>0){
            mDataList.clear();
            for (County county: mCountyList){
                mDataList.add(county.getmCountyName());

            }

            mArrayAdapter.notifyDataSetChanged();
            mListView.setSelection(0);
            mCurrentLevel = LEVEL_COUNTY;
        }else {
            int provinceCode = mSelectedProvince.getmProcvinceCode();
            int cityCode = mSelectedCity.getmCityCode();
            String address = "http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
            queryFromServer(address,"county");
        }
    }

    private void queryFromServer(String address,final String type){
        showProgressDialog();
        HttpUtil.sendOkhttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                boolean result = false;
                if ("province".equals(type)){
                    result = Utility.handleProvinceResponse(responseText);
                }else if ("city".equals(type)){
                    result = Utility.handleCityResponse(responseText,mSelectedProvince.getId());
                }else if ("county".equals(type)){
                    result = Utility.handleCountyResponse(responseText,mSelectedCity.getId());
                }

                if (result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)){
                                queryProvinces();
                            }else if ("city".equals(type)){
                                queryCities();
                            }else if ("county".equals(type)){
                                queryCounties();
                            }

                        }
                    });
                }
            }
        });
    }


    private void showProgressDialog(){
        if (mProgressDialog==null){
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.setCanceledOnTouchOutside(false);
        }
        mProgressDialog.show();
    }

    private void closeProgressDialog(){
        if (mProgressDialog!=null){
            mProgressDialog.dismiss();
        }
    }
}
